package com.example.rxtxdemo.rxtx;

import com.fazecast.jSerialComm.SerialPort;


public class SerialComm {

    /*public static void main(String[] args) throws InterruptedException {
        SerialComm serialComm = new SerialComm("COM3");
        serialComm.openPort();
        while (true) {
            byte[] bs = serialComm.writeAndRead("010300000002");
            Double[] d = Utils.analysisData(bs, 3, 5, 2);
            if (d != null) {
                for (Double a : d) {
                    System.out.println(a);
                }
            }

            Thread.sleep(1000);
        }
    }*/


    public SerialComm(String portDescriptor) {
        this.portDescriptor = portDescriptor;
    }

    public SerialComm(String portDescriptor, Integer baudRate) {
        this.portDescriptor = portDescriptor;
        this.baudRate = baudRate;
    }

    private String portDescriptor;
    private Integer baudRate;

    private SerialPort comPort;

    public boolean isOpen() {
        return comPort.isOpen();
    }

    /**
     * 打开串口
     *
     * @return 打开的状态
     */
    public boolean openPort() {
        return openPort(portDescriptor, baudRate);
    }

    /**
     * 打开串口
     *
     * @param portDescriptor COM口
     * @return 打开的状态
     */
    public boolean openPort(String portDescriptor) {
        return openPort(portDescriptor, null);
    }

    /**
     * 打开串口
     *
     * @param portDescriptor COM口
     * @param baudRate       波特率
     * @return 打开的状态
     */
    public boolean openPort(String portDescriptor, Integer baudRate) {
        comPort = SerialPort.getCommPort(portDescriptor);
        if (baudRate != null) {
            comPort.setBaudRate(baudRate);
        }
        if (!comPort.isOpen()) {
            return comPort.openPort();
        } else {
            return true;
        }
    }


    /**
     * 关闭串口
     *
     * @return
     */
    public boolean closePort() {
        if (comPort != null && comPort.isOpen()) {
            return comPort.closePort();
        }
        return true;
    }

    /**
     * 向com口发送数据并且读取数据
     */
    public byte[] writeAndRead(String content) {
        byte[] reslutData = null;

        if (!comPort.isOpen()) {
            return null;
        }

        try {
            int numWrite = comPort.writeBytes(SerialTools.hexToByteArray(content), SerialTools.hexToByteArray(content).length);
            if (numWrite > 0) {
                int i = 0;
                while (comPort.bytesAvailable() > 0 && i++ < 5) Thread.sleep(20);
                byte[] readBuffer = new byte[comPort.bytesAvailable()];
                int numRead = comPort.readBytes(readBuffer, readBuffer.length);
                if (numRead > 0) {
                    reslutData = readBuffer;
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return reslutData;
    }

}